package com.cmc.cloud.cmclink.doc.task;


import com.cmc.cloud.cmclink.doc.api.document.req.si.DraftConfirmDto;
import com.cmc.cloud.cmclink.doc.entity.*;
import com.cmc.cloud.cmclink.doc.mapper.BlnoMapper;
import com.cmc.cloud.cmclink.doc.service.si.BlnoService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * draft逾期未确认批处理，时间过了船名航次+港口的截改单时间的系统自动确认，确认人 system
 * 
 * @author heguo
 * @date 2025/09/24
 **/
@Component
@Slf4j
public class DraftConfirmTask {

    private static final DateTimeFormatter FORMATTER_AMEND = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Resource
    private BlnoService blnoService;
    @Resource
    private BlnoMapper blnoMapper;
    @XxlJob("DraftConfirmTaskHandler")
    public void draftConfirmTask() {
        LocalDateTime now = LocalDateTime.now();
        String localDateTime = now.format(FORMATTER_AMEND);
        XxlJobHelper.log("DraftConfirmTask begin,local date time :{}",localDateTime);
        while (true){
            List<Long> blIds = blnoMapper.selectDraftConfirmOverdueBlIds(localDateTime,1000);
            XxlJobHelper.log("System auto confirm draft list:{}",Arrays.toString(blIds.toArray()));
            if (!CollectionUtils.isEmpty(blIds)){
                blIds.forEach(b-> {
                    DraftConfirmDto draftConfirmDto = new DraftConfirmDto();
                    draftConfirmDto.setConfirmDate(now);
                    draftConfirmDto.setConfirmer("system");
                    draftConfirmDto.setBlId(b);
                    blnoService.draftConfirm(draftConfirmDto);
                });
            }
            if (CollectionUtils.isEmpty(blIds) || blIds.size() < 1000){
                break;
            }
        }
        XxlJobHelper.log("DraftConfirmTask end.");
    }
}
